package cn.yotta.user.web.autoconfiguration.provider.impl;

import cn.yotta.user.web.autoconfiguration.exception.UserLoginException;
import cn.yotta.user.web.autoconfiguration.provider.LoginUser;
import cn.yotta.user.web.autoconfiguration.provider.LoginUserLoadProvider;
import cn.yotta.user.web.autoconfiguration.provider.UserReadFromTokenProvider;
import cn.yotta.user.web.autoconfiguration.token.LoginTokenObtainStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author wyaoyao
 * @date 2023/3/10 17:13
 */
@Slf4j
public class DefaultLoginUserLoadProvider implements LoginUserLoadProvider {

    private final LoginTokenObtainStrategy loginTokenObtainStrategy;

    private final UserReadFromTokenProvider userReadFromTokenProvider;

    public DefaultLoginUserLoadProvider(LoginTokenObtainStrategy loginTokenObtainStrategy, UserReadFromTokenProvider userReadFromTokenProvider) {
        this.loginTokenObtainStrategy = loginTokenObtainStrategy;
        this.userReadFromTokenProvider = userReadFromTokenProvider;
    }

    @Override
    public LoginUser get(HttpServletRequest httpServletRequest) throws UserLoginException {
        // 获取用户登录的token
        final String token = loginTokenObtainStrategy.getToken(httpServletRequest);
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        return userReadFromTokenProvider.findUserByToken(token);
    }
}
